<template>
    <div>
        <el-select
            v-model="inputValue"
            :placeholder="placeholder"
            class="w100"
            clearable
            filterable
            :disabled="disabled"
            :multiple="multiple"
            :collapse-tags="multiple"
            :size="size"
            @change="onChange"
        >
            <el-option
                v-for="(el, idx) in list"
                :key="idx"
                :label="lodash.get(el, labelKey, '')"
                :value="el[valueKey]"
            />
        </el-select>
    </div>
</template>
<script>
import lodash from 'lodash'

export default {
    name: 'JSelect',
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        url: {
            type: String,
            default: () => ''
        },
        placeholder: {
            type: String,
            default: () => ''
        },
        valueKey: {
            type: String,
            default: () => 'id'
        },
        labelKey: {
            type: String,
            default: () => 'name'
        },
        value: {
            type: [String, Number, Array],
            default: () => ''
        },
        extParams: {
            type: Object,
            default: () => {
            }
        },
        size: {
            type: String,
            default: () => ''
        },
        multiple: {
            type: Boolean,
            default: () => false
        },
        disabled: {
            type: Boolean,
            default: () => false
        },
        localDatas: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            lodash,
            list: [],
            inputValue: ''
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(val) {
                if (this.multiple) {
                    this.inputValue = Array.isArray(this.value) ? this.value : (this.value ? this.value.split(',') : [])
                } else {
                    this.inputValue = Array.isArray(this.value) ? this.value.join(',') : this.value
                }
            }
        }
    },
    methods: {
        onChange() {
            const val = this.multiple ? this.inputValue.join(',') : this.inputValue
            this.$emit('change', val)
            this.$emit('input', val)
            this.$emit('update:model', val)
        }
    },
    created() {
        this.list = this.localDatas
    }
}
</script>
